package com.example.clsj.netty;

import cn.hutool.core.util.StrUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * @Author: cy
 * @Date: 2024/8/23
 */
public class NettyClient {
    private static final Logger log = LoggerFactory.getLogger(NettyClient.class);

    public static void createClient(String msg, String host, int port) {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap client = new Bootstrap();
            client.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sch) throws Exception {
                            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
                            int length = bytes.length;
                            String head = StrUtil.fillBefore(String.valueOf(length), '0', 8);
                            sch.writeAndFlush((head + msg).getBytes(StandardCharsets.UTF_8));
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            log.info("{}", msg);
                            ctx.close();
                        }


                    });

            ChannelFuture future = client.connect(host, port).sync();
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // Restore interrupted status
            log.error("NettyClient createClient was interrupted", e);
            throw new RuntimeException("NettyClient createClient was interrupted", e);
        } catch (Exception e) {
            log.error("NettyClient createClient error: ", e);
            throw new RuntimeException("NettyClient createClient error", e);
        } finally {
            group.shutdownGracefully().syncUninterruptibly();
        }
    }

}
